package com.dmy.common.config;

import com.dmy.chat.config.ChatServerConfig;
import com.dmy.chat.server.netty.ChatNettyServer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * create by huahuadelei for 2020/1/4
 */
@Component
@ConditionalOnProperty(value = "chat.netty",matchIfMissing = true)
@EnableConfigurationProperties(ChatServerConfig.class)
public class ChatNettyServerBean implements ApplicationListener<ApplicationEvent> {
    @Autowired
    private ChatServerConfig config;
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        ChatNettyServer server = null;
        if(applicationEvent instanceof ApplicationStartedEvent){
            try {
                server = ChatNettyServer.getInstance(config);
                server.start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if(applicationEvent instanceof ContextClosedEvent){
            if(server != null){
                try {
                    server.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
